import { VNode } from 'vue';
import { Component, Prop, Inject } from 'vue-property-decorator';
// import { MessageBox } from 'element-ui';

import {
  ConfigType,
  ClientAction,
  ViewContext,
  isString,
  noop,
  getControl,
} from '../../vendors/handie';

import BaseHeadlessWidget from '../base/Base';

@Component
export default class ActionHeadlessWidget extends BaseHeadlessWidget {
  @Inject({ from: 'viewContext', default: null })
  protected readonly context!: ViewContext;

  @Prop({ type: Object, default: () => ({}) })
  protected readonly action!: ClientAction;

  protected disabled: boolean = false;

  protected get config(): ConfigType {
    return this.action.config || {};
  }

  protected resolveContent(): VNode[] | string {
    const text = this.action.text || '';

    let { showIcon, iconOnly, icon } = this.config;

    if (showIcon === undefined) {
      showIcon = this.getCommonBehavior('action.showIcon');
    }

    if (iconOnly === undefined) {
      iconOnly = this.getCommonBehavior('action.iconOnly');
    }

    if (!showIcon || !icon) {
      return text;
    }

    const h = this.$createElement;
    const children: VNode[] = [h(getControl('Icon'), { props: { refs: icon } })];

    if (!iconOnly) {
      children.push(h('span', text));
    }

    return children;
  }

  protected onExecute(): void {
    const { danger, confirm, text, execute } = this.action;

    let beforeExecute: ((callback: () => Promise<void>) => void) | undefined;

    // if (danger || confirm) {
    //   beforeExecute = callback =>
    //     MessageBox.confirm(
    //       isString(confirm) ? (confirm as string) : `确定要${text || '执行此操作'}？`,
    //       '提示',
    //       { type: 'warning' },
    //     )
    //       .then(callback)
    //       .catch(noop);
    // }

    const executeAction = async () => {
      if (execute) {
        await Promise.resolve(execute(this.context, this));
      }
    };

    if (beforeExecute) {
      beforeExecute(executeAction);
    } else {
      executeAction();
    }
  }

  protected created(): void {
    const {
      disableWhenNoSelection = this.getCommonBehavior('action.disableWhenNoSelection', true),
    } = this.config;

    if (disableWhenNoSelection === false) {
      return;
    }

    const { context } = this.action;
    const batchOrBoth = context === 'batch' || context === 'both';

    this.disabled = batchOrBoth;

    if (batchOrBoth) {
      this.on(
        'change',
        value => (this.disabled = context === 'batch' ? value.length < 2 : value.length === 0),
      );
    }
  }
}
